package com.exonline.backstage.listener;

import com.sun.net.httpserver.HttpContext;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

@WebListener
public class SessionListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        System.out.println("listener started...");
        HttpSession session = se.getSession();
        ServletContext servletContext = session.getServletContext();
        Integer onlineUsers = (Integer) servletContext.getAttribute("onlineUser");
        if(onlineUsers == null){
            System.out.println("第一个在线用户");
            onlineUsers = 1;
        }else{
            System.out.println("在线用户+1");
            onlineUsers=onlineUsers + 1;
        }
        servletContext.setAttribute("onlineUser", onlineUsers);

    }
@Override
    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("session destroyed...");
        HttpSession session = se.getSession();
    Integer onlineUsers = (Integer) session.getServletContext().getAttribute("onlineUsers");
    session.setAttribute("onlineUsers", onlineUsers-1);
}

}
